#!/bin/bash

usage() {
    echo "Usage: $0 -u <urls_file> -d <download_dir>"
    exit 1
}

while getopts ":u:d:" opt; do
  case $opt in
    u) URI_FILE="$OPTARG" ;;
    d) DEST_DIR="$OPTARG" ;;
    *) usage ;;
  esac
done

if [ -z "$URI_FILE" ] || [ -z "$DEST_DIR" ]; then
    usage
fi

if [ ! -f "$URI_FILE" ]; then
    echo "URI file '$URI_FILE' not found!"
    exit 1
fi

mkdir -p "$DEST_DIR"

MAX_ATTEMPTS=3

# Count total lines (non-empty)
total=$(grep -cve '^\s*$' "$URI_FILE")
current=0

progress_bar() {
    local progress=$1
    local total=$2
    local width=40
    local percent=$(( 100 * progress / total ))
    local filled=$(( width * progress / total ))
    local empty=$(( width - filled ))
    printf "\r["
    for ((i=0; i<filled; i++)); do printf "#"; done
    for ((i=0; i<empty; i++)); do printf "-"; done
    printf "] %d/%d (%d%%)" "$progress" "$total" "$percent"
}

while IFS= read -r uri; do
    [ -z "$uri" ] && continue  # skip empty lines
    current=$((current+1))
    progress_bar $current $total
    hashid=$(basename "$uri")
    # Find a file in DEST_DIR whose base name (before first dash) matches hashid
    match_file=$(find "$DEST_DIR" -maxdepth 1 -type f -name "${hashid}-*" | head -n 1)
    match_path=""
    if [ -n "$match_file" ]; then
        match_path="$DEST_DIR/$match_file"
        echo -e "\nFile found: $match_path"
        if ! xz -t "$match_path" 2>/dev/null; then
            echo -e "\nCorrupted file detected: $match_path. Re-downloading..."
            rm -f "$match_path"
            redownload=1
        else
            echo -e "\nFile OK: $match_path"
            redownload=0
        fi
    else
        echo -e "\nNo local file for hash $hashid. Downloading..."
        redownload=1
    fi

    attempt=1
    while [ "$redownload" -eq 1 ] && [ $attempt -le $MAX_ATTEMPTS ]; do
        echo -e "\nDownloading (attempt $attempt): $uri"
        wget --content-disposition -P "$DEST_DIR" "$uri"
        # Find the newest file with hashid prefix
        match_file=$(find "$DEST_DIR" -maxdepth 1 -type f -printf '%f\n' | grep -E "^${hashid}-" | xargs -I{} stat -c "%Y %n" "$DEST_DIR/{}" | sort -nr | head -n1 | awk '{print $2}')
        if [ -z "$match_file" ]; then
            echo "Download failed: No file found with hash $hashid after download."
            attempt=$((attempt+1))
            continue
        fi
        if xz -t "$match_file" 2>/dev/null; then
            echo "Downloaded and verified: $match_file"
            redownload=0
        else
            echo "Download failed or file still corrupted: $match_file"
            rm -f "$match_file"
            attempt=$((attempt+1))
        fi
    done
    if [ "$redownload" -eq 1 ]; then
        echo "Failed to download a valid file for $hashid after $MAX_ATTEMPTS attempts."
    fi

done < "$URI_FILE"
echo # for newline after progress bar 